package com.kamistoat.meimeimall.meimeimallseckill.controller;

import com.kamistoat.meimeimall.common.utils.PageUtils;
import com.kamistoat.meimeimall.common.utils.Query;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

//import org.apache.shiro.authz.annotation.RequiresPermissions;
import com.kamistoat.meimeimall.common.annotation.DubboAndHTTPExceptionCatch;
import com.kamistoat.meimeimall.common.annotation.LoginRequired;
import com.kamistoat.meimeimall.common.constant.SecKillConstant;
import com.kamistoat.meimeimall.common.dubboInterface.SecKillDubboInterface;
import com.kamistoat.meimeimall.meimeimallseckill.service.SeckillSessionService;
import com.kamistoat.meimeimall.meimeimallseckill.entity.SeckillSkuRelationEntity;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.dubbo.config.annotation.Reference;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import com.kamistoat.meimeimall.meimeimallseckill.service.SeckillSkuRelationService;
import com.kamistoat.meimeimall.common.utils.R;


/**
 * 秒杀活动商品关联
 *
 * @author kamistoat
 * @email linjianshanke@163.com
 * @date 2021-09-12 16:19:46
 */
@Api(tags="秒杀活动商品关联数据库操作")
@RestController
@RequestMapping("seckillskurelation")
public class SeckillSkuRelationController {
    protected Logger logger = LoggerFactory.getLogger(SeckillSkuRelationController.class);

    @Autowired
    SeckillSkuRelationService seckillSkuRelationService;
    @Autowired
    SeckillSessionService seckillSessionService;

    @Reference
    SecKillDubboInterface secKillDubboInterface;

    /**
     * 列表
     */
    @ApiOperation("从数据库获取列表")
    @GetMapping("/list")
    @LoginRequired
    @DubboAndHTTPExceptionCatch
    public R list(@RequestParam Map<String, Object> params) {
        PageUtils page = seckillSkuRelationService.queryPage(params);

        return R.ok().put("page", page);
    }


    /**
     * 信息
     */
    @ApiOperation("从数据库查询指定的POJO")
    @GetMapping("/seckill_sku_relation_info")
    @LoginRequired
    @DubboAndHTTPExceptionCatch
    public R info(@RequestParam("id") Long id) {
        SeckillSkuRelationEntity seckillSkuRelation = seckillSkuRelationService.getById(id);

        return R.ok().put("seckillSkuRelation", seckillSkuRelation);
    }

    /**
     * 保存.除了进MySQL，还检查该秒杀是否位于3天以内，如果是，同时在redis进行缓存。
     */
    @ApiOperation("向数据库保存POJO")
    @PutMapping("/seckill_sku_relation_info")
    @LoginRequired
    @DubboAndHTTPExceptionCatch
    public R save(@RequestBody SeckillSkuRelationEntity seckillSkuRelation) {
        R status = seckillSkuRelationService.checkRelation(seckillSkuRelation);
        if ((int) status.get("code") == 0) {
            seckillSkuRelationService.save(seckillSkuRelation);
            // secKillFeignService.delete_ReUp_RedisSessions(getRedisSessionKey(new Long[]{seckillSkuRelation.getPromotionSessionId()}));
            R resultR = secKillDubboInterface.deleteAndReUpToRedis(getRedisSessionKey(new Long[]{seckillSkuRelation.getSessionId()}));
            if (resultR.getCode() != 0) {
                logger.error(resultR.getMsg());
            }
            return resultR;
        } else if ((int) status.get("code") == 2) {
            SeckillSkuRelationEntity sumRelation = (SeckillSkuRelationEntity) status.get("data");
            seckillSkuRelationService.updateById(sumRelation);
            // secKillFeignService.delete_ReUp_RedisSessions(getRedisSessionKey(new Long[]{sumRelation.getPromotionSessionId()}));
            R resultR = secKillDubboInterface.deleteAndReUpToRedis(getRedisSessionKey(new Long[]{sumRelation.getSessionId()}));
            if (resultR.getCode() != 0) {
                logger.error(resultR.getMsg());
            }
            return resultR;
        } else {
            return status;
        }
    }

    /**
     * 修改.除了进MySQL，还检查该秒杀是否位于3天以内，如果是，同时在redis进行缓存。
     */
    @ApiOperation("向数据库更新POJO")
    @PostMapping("/seckill_sku_relation_info")
    @LoginRequired
    @DubboAndHTTPExceptionCatch
    public R update(@RequestBody SeckillSkuRelationEntity seckillSkuRelation) {
        seckillSkuRelationService.updateById(seckillSkuRelation);
        // secKillFeignService.delete_ReUp_RedisSessions(getRedisSessionKey(new Long[]{seckillSkuRelation.getPromotionSessionId()}));
        R resultR = secKillDubboInterface.deleteAndReUpToRedis(getRedisSessionKey(new Long[]{seckillSkuRelation.getSessionId()}));
        if (resultR.getCode() != 0) {
            logger.error(resultR.getMsg());
        }
        return resultR;
    }

    /**
     * 删除.除了进MySQL，还检查该秒杀是否位于3天以内，如果是，同时在redis进行缓存。
     */
    @ApiOperation("从数据库删除指定优惠券")
    @DeleteMapping("/seckill_sku_relation_info")
    @LoginRequired
    @DubboAndHTTPExceptionCatch
    public R delete(@RequestBody Long[] ids) {
        Long sessionId = seckillSkuRelationService.getById(ids[0]).getSessionId();
        seckillSkuRelationService.removeByIds(Arrays.asList(ids));
        // secKillFeignService.delete_ReUp_RedisSessions(getRedisSessionKey(new Long[]{sessionId}));
        R resultR = secKillDubboInterface.deleteAndReUpToRedis(getRedisSessionKey(new Long[]{sessionId}));
        if (resultR.getCode() != 0) {
            logger.error(resultR.getMsg());
        }
        return resultR;
    }


    /**
     * 根据ids制作redis keyList
     *
     * @param ids
     * @return
     */
    public List<String> getRedisSessionKey(@RequestParam Long[] ids) {
        return seckillSessionService.listByIds(Arrays.asList(ids)).stream().map(seckillSessionEntity -> {
            String key = SecKillConstant.SEC_SESSION_PREFIX
                    + seckillSessionEntity.getStartTime().getTime() + "_" + seckillSessionEntity.getEndTime().getTime();
            return key;
        }).collect(Collectors.toList());
    }

}
